<template>
	<el-container v-if="isAlready" style="background-color: #fff;">
		<el-header  style="padding-top: 0px;padding-bottom: 0px;height: 60px;">
			<fsButton ref="button" plain size="default" :buttons="buttons" @clickHandler="buttonHandler"></fsButton>
		</el-header>
		<div style="float: left;width: 98%;background-color: rgb(249, 249, 249);padding: 8px 15px 5px 15px;margin-top: 3px;
		border: 1px rgba(0, 0, 0, .08) solid;margin-left: 1%;">
				<div class="left-panel" style="float: left;width: 70%;">
					<div style="margin-left: -2px;float: left;">
						<img class="topblockimg" src="img/pandian-icon.png"/>
					</div>
					<div style="font-size: 14px;width: 60px;margin-top:10px;margin-left: 10px;float: left;">盘点任务</div>
					<div style="width: 100%;margin-top: 8px;margin-left: 100px;">
						<sc-select-filter-check ref="scSelectFilter" :data="filterData" :selectedValues="selectedValues" :label-width="80" @on-change="tabChange">
						</sc-select-filter-check>
					</div>
				</div>
				<div class="right-panel" style="float: right;width: 30%;">
					<ex-search ref="search" :searches="searches" @searchOk="searchHandler" default-code="code" placeholder="请输入盘点任务编码" :fixedParam=fixedParams></ex-search>
				</div>
			</div>
		<el-main class="nopadding">

			<ex-table :auto-refresh="false" id="checkTaskTable" ref="table" :columns="columns" :url="this.$API.asset.checkTaskApi.page.url" :refs="this.$refs" search="search" @columnClick="columnClickHandler"></ex-table>
		</el-main>
	</el-container>
	<save-dialog ref="saveDialog" @success="refreshPage"/>
	<edit-dialog ref="editDialog" @success="searchHandler"/>
</template>

<script>
import saveDialog from '@/views/asset/check/checkTask/save.vue'
import editDialog from '@/views/asset/check/checkTask/edit.vue'
import ExTable from "@/components/exTable/index.vue";
import ExSearch from "@/components/exSearch/index.vue";
import ExTreeNavigation from "@/components/exSearchTree/index.vue";
import ExSearchTree from "@/components/exSearchTree/index.vue";
import scSelectFilter from "@/components/scSelectFilter/index.vue";
import scSelectFilterCheck from "@/components/scSelectFilterCheck/index.vue";
import tool from "@/utils/tool";
import BaseTemplate from "@/utils/baseTemplate";
import useTabs from "@/utils/useTabs";
export default {
	name: '资产盘点',
	components: {
		scSelectFilter,
		scSelectFilterCheck,
		ExSearchTree,
		ExTreeNavigation,
		ExSearch,
		ExTable,
		saveDialog,
		editDialog,
	},
	data() {
		return {
			dialog: {
				save: false,
				permission: false,
			},
			isAlready: false,
			apiObj: [],
			buttons: [
				{name: this.$t('button.add'), icon: "el-icon-plus", click: "add", permission: "add"},
				{name: "导出", icon: "el-icon-download", click: "export",type: "info", permission: "export"},
				{name: this.$t('button.delete'), icon: "el-icon-delete", click: "delCheckTask", type: "info", permission: "delete"},
				{name: "强制删除", icon: "el-icon-delete", click: "forceDelete", type: "info", permission: "forceDelete"},
			],
			searches: [
				{type: "input", name: "任务编码", code: "code", placeholder: "请输入任务编码", maxlength: 30, showLimit: true},
				{type: "input", name: "任务名称", code: "name", placeholder: "请输入任务名称"},
				{type: "select", name: "任务类型", code: "taskType", placeholder: "请选择任务类型", dictCode:'TASK_TYPE'},
				{type: "tree-select", name: "制定部门", code: "createOrgIds", placeholder: "请选择制定部门", dictCode:'SysOrganization',checkStrictly:true,multiple:true,priKey:true},
				{type: "selector", name: "制定人", code: "createUser", placeholder: "请选择制定人", dictCode:'SysUser',priKey:true},
				{type: "daterange", name: "制定日期", code: "createTimeStart,createTimeEnd", placeholder: "请选择制定日期", valueFormat:"YYYYMMDD" , formatter:"YYYY-MM-dd",range:365},
				{type: "daterange", name: "开始日期", code: "startDateStart,startDateEnd", placeholder: "请选择开始日期", valueFormat:"YYYYMMDD", formatter:"YYYY-MM-dd",range:365},
			],
			columns: [
			{code: "操作", name: "操作", width: "150",
					click:[
						{label:"详情",event:'showDetail',type: "info", permission: "",class:"checktaskbtn"},
						// {label:"编辑",icon:"el-icon-edit",event:'detailedit',type: "info", permission: ""},
						{label:"延长盘点时间",event:'editData',type: "info", permission: "editData",class:"checktaskbtn"}
					]
				},
				{code: "status", name: "状态", width:"85",sortable: true,formatter:"DICT",key: "TASK_STATUS"},
				{code: "code", name: "任务编码", width:"150",sortable:true},
				{code: "name", name: "任务名称", width:"200",click:"show1"},
				{code: "taskType", name: "任务类型", width:"120",formatter:"DICT",key: "TASK_TYPE"},
				{code: "startDate", name: "开始时间", width:"110",sortable:true,formatter: "DATE"},
				{code: "endDate", name: "结束时间", width:"110",sortable:true,formatter: "DATE"},
				{code: "createOrg", name: "制定部门", width:"200",sortable:true,formatter: "DICT",key: "SysOrganization"},
				{code: "createUser", name: "制定人", width:"100",sortable:true,formatter: "DICT",key: "SysUser"},
				{code: "createTime", name: "制定时间", width:"200",sortable:true,formatter: "DATETIME"},
				{code: "description", name: "盘点任务备注", width:"300"},
			],
			filterData: [
				{
					title: "【任务状态】",
					key: "status",
					multiple: false,
					options: [
						{
							label: "全部(0)",
							value: ""
						},
						{
							label: "生成中(0)",
							value: "3"
						},
						{
							label: "未开始(0)",
							value: "2"
						},
						{
							label: "进行中(0)",
							value: "0"
						},
						{
							label: "结束(0)",
							value: "1"
						},
						{
							label: "异常(0)",
							value: "4"
						},
					]
				},
			],
			parentLevelCode:"",
			taskStatus:"",
			loginUsers: tool.current.user(),
			fixedParams: {
			},
			readDeptIds: this.$TOOL.current.readDeptIds(),
			totalCount:0,
			selectedValues: [],
			notStartCount:0,
			generateCount:0,
			usingCount:0,
			isFirstPage: false,
			endCount:0,
			isManage: false,
			errorCount:0,
		}
	},
	created() {
		let routeParams = this.$store.state.routeParams[this.$route.query.key];
		if (routeParams) {
			if (routeParams.title) {
				useTabs.setTitle(routeParams.title);
				document.title = routeParams.title;
			}
			if (routeParams.fixedParams) {
				let checkStatus = routeParams.fixedParams.status;
				if(typeof checkStatus !== 'undefined' && checkStatus != null && checkStatus !== ''){
					this.taskStatus = checkStatus;
					this.fixedParams.status = checkStatus;
					this.taskStatus = checkStatus;
					this.filterData[0].options = [
						{
							label: "进行中(0)",
							value: "0"
						}
					]
					this.isFirstPage = true;
				}
				if(routeParams.fixedParams.searchType) {
					this.fixedParams.searchType = routeParams.fixedParams.searchType;
				}
			}
		}
		this.fixedParams.queryUser = this.loginUsers.id;
		this.fixedParams.readDeptIds = this.readDeptIds;
		this.isAlready =true
	},
	mounted() {
		let queryParams = {}
		queryParams.readDeptIds = this.readDeptIds;
		queryParams.status = this.taskStatus;
		queryParams.queryUser = this.loginUsers.id;
		this.loadCountByStatus(queryParams);
		this.getCheckManageRole();
		this.$refs.table.refresh(queryParams);
	},
	beforeMount() {
	},
	methods: {
		buttonHandler(index, name) {
			this.$options.methods[name](this, index);
		},
		async searchTreeHandler(data) {
			let queryParams = {pathCode:data.levelCode}
			this.parentLevelCode= data.levelCode;
			await this.$refs.table.refresh(queryParams);
		},
		async getCheckManageRole() {
			let queryParams = {}
			let rsp = await this.$API.asset.checkTaskApi.getCheckManageRole.post(queryParams);
			if (rsp.code === 2000) {
				if(rsp.data === 1 || this.readDeptIds.includes('0000000')) {
					this.isManage = true;
				}
			}
		},
		async loadCountByStatus(queryParams) {
			let rsp = await this.$API.asset.checkTaskApi.getCountByStatus.post(queryParams);
			if (rsp.code === 2000) {
				this.totalCount = rsp.data.totalCount;
				this.usingCount = rsp.data.usingCount;
				this.endCount = rsp.data.endCount;
				this.notStartCount = rsp.data.notStartCount;
				this.generateCount = rsp.data.generateCount;
				this.errorCount = rsp.data.errorCount;
				if(this.isFirstPage){
					let optionsData = [
						{
							label: "进行中(" + rsp.data.usingCount + ")",
							value: "0"
						},
					];
					Object.assign(this.filterData[0].options, optionsData);
				}else{
					let optionsData = [
						{
							label: "全部(" + rsp.data.totalCount + ")",
							value: ""
						},
						{
							label: "生成中(" + rsp.data.generateCount + ")",
							value: "3"
						},
						{
							label: "未开始(" + rsp.data.notStartCount + ")",
							value: "2"
						},
						{
							label: "进行中(" + rsp.data.usingCount + ")",
							value: "0"
						},
						{
							label: "结束(" + rsp.data.endCount + ")",
							value: "1"
						},
						{
							label: "异常(" + rsp.data.errorCount + ")",
							value: "4"
						},
					];
					Object.assign(this.filterData[0].options, optionsData);
				}

			}
		},
		async searchHandler() {
			let queryParams = {pathCode: this.parentLevelCode}
			// let queryParamst = {};
			// Object.assign(queryParamst, this.$refs.search.searchParams());
			// this.loadCountByStatus(queryParamst);
			queryParams.status = this.taskStatus;
			await this.$refs.table.refresh(queryParams);
		},
		columnClickHandler(name,data){
			this.$options.methods[name](this, data);
		},
		//添加
		add(_this) {
			let data = {
				parentLevelCode: _this.parentLevelCode,
				entityName:_this.$CONSTANT.entity.FamsAssetCheckTask.name,
			};
			let resultData = {
				isCanEdit: true,
				data : data
			}
			_this.$nextTick(() => {
				_this.$refs.saveDialog.open(resultData);
			})
		},
		//编辑
		async editData(_this, row) {
			//如果创建部门在当前用户管理范围内
			if (row.createUser === _this.loginUsers.id) {
				//可操作
			} else {
				_this.$message.warning("只能变更自己创建的盘点任务的时间");
				return;
			}
			if (row.status === "1") {
				_this.$message.warning("结束的任务无法变更时间");
				return;
			}
			// if(row.status == "1"){
			// 	_this.$message.warning("已结束的盘点任务不能变更时间");
			// 	return;
			// }
			_this.$nextTick(() => {
				_this.$refs.editDialog.open(row);
			})
		},
		//编辑
		detailedit(_this,row) {
			if(row.createUser === _this.loginUsers.id){
				//可操作
			}else{
				_this.$message.warning("只能编辑自己创建的盘点任务");
				return;
			}
			let resultData = {
				isCanEdit: true,
				data : row
			}
			_this.$nextTick(() => {
				_this.$refs.saveDialog.open(resultData);
			})
		},
		//查看
		showDetail(_this,row) {
			let resultData = {
				isCanEdit: false,
				data : row
			}
			_this.$nextTick(() => {
				_this.$refs.saveDialog.open(resultData);
			})
		},
		//查看
		async show1(_this, row) {
			_this.searchCheckDocument(row.code,row.id,row.name,row.status,row.createUser,row.isIncludeInvisible);
		},
		searchCheckDocument(item,taskId,taskName,taskStatus,taskCreateUser,isIncludeInvisible) {
			let title = "盘点任务"+item+"盘点单";
			let roleManage = this.isManage;
			//跳转到搜索台账页面
			let fromRouteId = this.$TOOL.crypto.MD5(this.$route.path);//当前页面的路由地址
			let key = this.$TOOL.crypto.MD5(item);//可以做为key的关键字段或内容
				//设置搜索参数
			let routeParams = {
				id: key,
				title: title,
				fixedParams:{
					taskId:taskId,
					taskName:taskName,
					taskCode:item,
					searchType: this.fixedParams.searchType,
					taskStatus:taskStatus,
					taskCreateUser: taskCreateUser,
					isIncludeInvisible: isIncludeInvisible,
					isManage: roleManage
				},//固定搜索参数，打开页面后，用户通过搜索界面的清空按钮无法清除
			};
			this.$store.dispatch("addRouteParams", routeParams);
			this.$router.push({
				name: "toCheckDocument",
				params: {fromRouteId: fromRouteId, key: key}
			});
		},
		//批量删除
		async delCheckTask(_this, index) {
			let selections = _this.$refs.table.selections();
			if (selections.length === 0) {
				let confirm = await _this.$confirm('`确定删除所有盘点任务吗？如果删除则任务下的盘点单数据均会被删除', '警告', {type: 'warning'}).then(() => {
					return true;
				}).catch(() => {
					return false;
				});
				if (!confirm) {
					return;
				}
				let queryPrams = {
				}
				_this.$refs.button.loading(index, true);
				Object.assign(queryPrams, _this.$refs.table.queryParams());
				queryPrams.createUser = _this.loginUsers.id;
				queryPrams.status = _this.taskStatus;
				let rsp = await _this.$API.asset.checkTaskApi.deleteByQuery.post(queryPrams);
				if (rsp.code === 2000) {
					_this.$message.success(_this.$t("code." + rsp.code));
					_this.refreshPage();
					_this.$refs.button.loading(index, false);
				} else {
					_this.$refs.button.loading(index, false);
				}
			} else {
				_this.$confirm(`确定删除选中的 ${selections.length} 项盘点任务吗？如果删除则任务下的盘点单数据均会被删除`, '警告', {
					type: 'warning'
				}).then(async () => {
					let array = [];
					for (let index = 0; index < selections.length; index++) {
						const element = selections[index];
						if ((element.status === "2" || element.status === "3"|| element.status === "4") && element.createUser === _this.loginUsers.id) {
							array.push(element.id);
						}
					}
					if (array.length === 0) {
						_this.$message.warning("只允许删除本人创建的未开始或者未结束的盘点任务");
						return;
					}
					_this.$refs.button.loading(index, true);
					let rsp = await _this.$API.asset.checkTaskApi.deleteByIds.post(array);
					if (rsp.code === 2000) {
						_this.$message.success(_this.$t("code." + rsp.code));
						_this.refreshPage();
						_this.$refs.button.loading(index, false);
					} else {
						_this.$refs.button.loading(index, false);
					}
				}).catch(() => {
					_this.$refs.button.loading(index, false);
				});
			}

		},
		//批量删除
		forceDelete(_this, index) {
			let selections = _this.$refs.table.selections();
			if (selections.length === 0) {
				_this.$message.warning(_this.$t("common.please_select_data"));
				return;
			}
			_this.$confirm(`确定删除选中的 ${selections.length} 项盘点任务吗？如果删除则任务下的盘点单数据均会被删除`, '警告', {
				type: 'warning'
			}).then(async () => {
				_this.$refs.button.loading(index, true);
				let array = [];
				for (let index = 0; index < selections.length; index++) {
					const element = selections[index];
					array.push(element.id);
				}
				let rsp = await _this.$API.asset.checkTaskApi.deleteByIds.post(array);
				if (rsp.code === 2000) {
					_this.$message.success(_this.$t("code." + rsp.code));
					_this.refreshPage();
					_this.$refs.button.loading(index, false);
				}else{
					_this.$refs.button.loading(index, false);
				}
			}).catch(() => {
				_this.$refs.button.loading(index, false);
			});
		},
		//导出
		async export(_this,index) {
			_this.$refs.button.loading(index,true);
			let queryPrams = {
			};
			queryPrams.status = _this.taskStatus;
			let exportApi = _this.$API.asset.checkTaskApi.exportData;
			let exTableRef = _this.$refs.table;
			let exportBtnRef = _this.$refs.button;
			let exportBtnIndex = index;
			await BaseTemplate.export(_this, exportApi, queryPrams, exportBtnRef, exportBtnIndex, exTableRef);
			_this.$refs.button.loading(index,false);
		},
		//刷新页面
		refreshPage() {
			this.searchHandler();
			let queryParams = {}
			queryParams.status = this.taskStatus;
			queryParams.readDeptIds = this.readDeptIds;
			queryParams.queryUser = this.loginUsers.id;
			this.loadCountByStatus(queryParams);
		},
		//标签切换
		async tabChange(name){
			this.taskStatus = name.status;
			let queryPrams = {};
			Object.assign(queryPrams, this.$refs.table.queryParams());
			queryPrams.status = this.taskStatus;
			await this.$refs.table.refresh(queryPrams);
		},
	}
}

</script>
<style scoped>
.topblockimg {
   height: 35px;
   width: 35px;

}
</style>
